package product

import (
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/product"
	"gitcode.com/G-YT/iHealth25/server/model/product/request"
)

type ProductService struct{}

// CreateProduct 创建商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) CreateProduct(product *product.Product) (err error) {
	err = global.GVA_DB.Create(product).Error
	return err
}

// DeleteProduct 删除商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) DeleteProduct(ID string) (err error) {
	err = global.GVA_DB.Delete(&product.Product{}, "id = ?", ID).Error
	return err
}

// DeleteProductByIds 批量删除商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) DeleteProductByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]product.Product{}, "id in ?", IDs).Error
	return err
}

// UpdateProduct 更新商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) UpdateProduct(productInfo product.Product) (err error) {
	err = global.GVA_DB.Model(&product.Product{}).Where("id = ?", productInfo.ID).Updates(&productInfo).Error
	return err
}

// GetProduct 根据ID获取商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) GetProduct(ID string) (product product.Product, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&product).Error
	return
}

// GetProductDetail 根据ID获取商品详情（无鉴权）
// Author [yourname](https://github.com/yourname)
func (p *ProductService) GetProductDetail(ID string) (product product.Product, err error) {
	err = global.GVA_DB.Where("id = ? AND status = ?", ID, true).First(&product).Error
	return
}

// GetProductInfoList 分页获取商品管理记录
// Author [yourname](https://github.com/yourname)
func (p *ProductService) GetProductInfoList(info request.ProductSearch) (list []product.Product, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&product.Product{})
	var products []product.Product
	// 如果有条件搜索 下方会自动创建搜索语句
	if len(info.CreatedAtRange) == 2 {
		db = db.Where("created_at BETWEEN ? AND ?", info.CreatedAtRange[0], info.CreatedAtRange[1])
	}

	if info.Name != nil && *info.Name != "" {
		db = db.Where("name LIKE ?", "%"+*info.Name+"%")
	}
	if info.ProductType != 0 {
		db = db.Where("product_type = ?", info.ProductType)
	}
	if info.Status != nil {
		db = db.Where("status = ?", *info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["id"] = true
	orderMap["created_at"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&products).Error
	return products, total, err
}
